package com.smssalama.storage.framework;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.bouncycastle.crypto.CryptoException;

import com.smssalama.security.Security;

/**
 * Storage encryptor that uses an array of byte
 * 
 * @author Arnold P. Minde
 */
public class KeyStorageEncryptor extends StorageEncryptor {
	private byte[] _key;

	public KeyStorageEncryptor(byte[] key) {
		this._key = key;
	}

	public byte[] getKey() {
		return this._key;
	}

	public byte[] encrypt(byte[] data) throws IOException {
		byte[] encrypted = Security.encrypt(getKey(), data);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DataOutputStream stream = new DataOutputStream(out);
		int size = encrypted.length;
		stream.writeInt(size);
		stream.write(encrypted);
		return out.toByteArray();
	}

	public byte[] decrypt(byte[] data) throws IOException, CryptoException {
		ByteArrayInputStream in = new ByteArrayInputStream(data);
		DataInputStream stream = new DataInputStream(in);
		byte[] encrypted = null;
		int size = stream.readInt();
		encrypted = new byte[stream.available()];
		int read = stream.read(encrypted);
		if (read != size) {
			throw new IOException(
					"An error occured while decrypting. Expected " + size
							+ " bytes, found " + read + " bytes");
		}
		byte[] decrypted = Security.decrypt(getKey(), encrypted);
		// return only expected size
		byte[] result = new byte[size];
		System.arraycopy(decrypted, 0, result, 0, size);
		return result;
	}

}
